<template>
  <el-aside :width="isCollapse ? '64px' : '200px'">
    <el-scrollbar wrap-class="scrollbar-wrapper">
      <template v-if="!permissionStore.isReady">
        <div class="loading-text">路由加载中...</div>
      </template>
      <el-menu
        v-else-if="processedRoutes.length > 0"
        :default-active="activeMenu"
        background-color="#001529"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
        :collapse="isCollapse"
        :collapse-transition="false"
        router
        unique-opened
      >
        <sidebar-item
          v-for="route in processedRoutes"
          :key="route.path"
          :item="route"
          :base-path="route.path"
        />
      </el-menu>
      <template v-else>
        <div class="loading-text">没有可用的路由</div>
      </template>
    </el-scrollbar>
  </el-aside>
</template>

<script setup>
import { computed, onMounted, watchEffect } from 'vue'
import { useRoute } from 'vue-router'
import SidebarItem from './SidebarItem.vue'
import { usePermissionStore } from '@/stores/permission'

const permissionStore = usePermissionStore()
const route = useRoute()

// 处理后的路由数据
const processedRoutes = computed(() => {
  if (!permissionStore.isReady) return []

  const filterRoutes = (routes) =>
    routes
      .filter((route) => {
        const hasVisibleChildren = route.children?.some((child) => !child.meta?.hidden)
        return !route.meta?.hidden && (route.component || hasVisibleChildren)
      })
      .map((route) => ({
        ...route,
        path: route.path?.replace(/^\//, '') || '',
        children: route.children ? filterRoutes(route.children) : []
      }))

  return filterRoutes(permissionStore.routes)
})

// 当前激活菜单
const activeMenu = computed(() => {
  return route.meta.activeMenu || route.path
})

// 接收折叠状态
const props = defineProps({
  isCollapse: {
    type: Boolean,
    default: false
  }
})

// 调试日志
onMounted(() => {
  console.log('当前权限路由:', permissionStore.routes)
  console.log('处理后路由:', processedRoutes.value)
})

watchEffect(() => {
  console.log('权限路由是否准备就绪:', permissionStore.isReady)
  console.log('权限路由:', permissionStore.routes)
  console.log('处理后路由:', processedRoutes.value)
})
</script>

<style lang="scss" scoped>
.el-aside {
  transition: width 0.3s ease;

  .el-menu {
    border-right: none;
    width: 100%; /* 确保宽度占满整个侧边栏 */
  }
}

.loading-text {
  color: #fff;
  padding: 20px;
  text-align: center;
  font-size: 14px;
}
</style>